using Godot;
using MyKindom.BuildingSystem;
using MyKindom.GameError;
using System;

namespace BuildingSystem
{
    public partial class BuildingPlacer : Node2D
    {
        [Export]
        public TileMap constructionLayer;   // The tilemap object of construction

        [Export]
        public int buildingLayerIndex { get; set; }    // The index of which layer to place the building

        [Export]
        public bool buildingPlacerSwitch = false;     // The switch of place building

        private Building currentBuilding;
        private TileMapPattern _currentTileMapPattern;

        public int GetBuilding(Building building)
        {
            if (building == null || building.GetBuildingName() == "")
            {
                GD.PushError("Error: The building is Empty");
                return (int)GameErrorCode.OPERATE_FAILED;
            }

            currentBuilding = building;
            GD.Print("Info: Get building success");
            return (int)GameErrorCode.OPERATE_SUCCESS;
        }

        public override void _Process(double delta)
        {
            if (Input.IsActionJustPressed("KeyBoardPressE"))
            {
                buildingPlacerSwitch = true;
            }
            if (Input.IsActionJustPressed("KeyBoardPressC"))
            {
                buildingPlacerSwitch = false;
            }

            if (buildingPlacerSwitch && Input.IsActionJustPressed("MouseLeftClick"))
            {
                PlaceBuilding(currentBuilding);
            }
        }

        public int PlaceBuilding(Building buildingData)
        {
            Vector2 mousePos = GetGlobalMousePosition();
            Vector2I mapPosFromMousePos = constructionLayer.LocalToMap(mousePos);

            int ret = PlaceBuildingAtPosition(mapPosFromMousePos, buildingData);
            if (ret != (int)GameErrorCode.OPERATE_FAILED)
            {
                return (int)GameErrorCode.OPERATE_SUCCESS;
            }
            GD.PrintErr("Error: Failed to place building.");
            return (int)GameErrorCode.OPERATE_FAILED;
        }

        public int PlaceBuildingAtPosition(Vector2I placePosition, Building buildingData)
        {
            try
            {
                Vector2I tilePosition = buildingData.GetTileMapPosition();
                int tileSetIndex = buildingData.GetBuildingTileSetIndex();
                constructionLayer.SetCell(buildingLayerIndex, placePosition, tileSetIndex, tilePosition);

                return (int)GameErrorCode.OPERATE_SUCCESS;
            }
            catch
            {
                GD.PushError("Error: Failed to palce building at target position");
                return (int)GameErrorCode.OPERATE_FAILED;
            }
        }
    }
}
